<template>
  <!-- 图片按钮 -->
  <div class="img-btn" @click="showDialog">
    <img :src='coverImageUrl' alt="">
    <!-- 点击图片出现对话框 -->
    <el-dialog
      :append-to-body='true'
      title="选择素材"
      :visible.sync="dialogVisible">
      <!-- 弹窗后出现的头部内容 -->
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="全部" name="images">
          <!-- 图片列表开始 -->
          <el-row :gutter="10">
            <el-col :span="6" class="img_item" v-for="image in images" :key='image.id' @click.native="imgAddress(image)">
                <el-image
                  :class="{selected: curImgUrl === image.url}"
                  style="height:180px;width:180px"
                  :src="image.url"
                  fit="cover"></el-image>
            </el-col>
          </el-row>
          <!-- 图片列表结束 -->
        </el-tab-pane>
        <!-- 上传素材区域开始 -->
        <el-tab-pane label="上传素材" name="uploads">
          <el-upload
            class="avatar-uploader"
            action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
            :headers= headers
            name = 'image'
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-image v-if="imageUrl" :src="imageUrl" @load="slowLoad" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
         <!-- 上传素材区域结束 -->
      </el-tabs>
      <!-- 分页区域 -->
      <el-pagination
        @current-change='pageChange'
        style="margin-top:10px"
        background
        layout="prev, pager, next"
        :total="total_count">
      </el-pagination>
     <!-- 弹窗后出现的底部内容 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="imgConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 解决图片初始裂开问题
import defaultImageUrl from '@/assets/default.png'
export default {
  name: 'MyCover',
  props: ['value'],
  data () {
    return {
      coverImageUrl: this.value || defaultImageUrl,
      curImgUrl: '',
      activeName: 'images',
      collected: '全部',
      images: [],
      page: 1,
      total_count: 0,
      dialogVisible: false,
      imageUrl: '',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    }
  },
  methods: {
    // 加载图片
    async loadImage () {
      const params = this.buildParams()
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/images',
          method: 'get',
          params
        })
        console.log('获取图片成功', res)
        this.images = res.data.data.results
        this.total_count = res.data.data.total_count
      } catch (err) {
        console.log(err)
      }
    },
    // 构造查询参数
    buildParams () {
      const params = {
        collect: this.collected === '收藏',
        page: this.page,
        per_page: 10
      }
      return params
    },
    // 用户点击全部和收藏的反应
    hcollected () {
      this.page = 1
      this.loadImage()
    },
    // 分页加载
    pageChange (currentPage) {
      console.log('当前是第', currentPage)
      this.page = currentPage
      // 依据当前页面。发送请求获取数据
      this.loadImage()
    },
    // 点击弹出上传图片框
    showDialog () {
      this.dialogVisible = true
      this.imageUrl = ''
      this.curImgUrl = ''
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data.url
      console.log('上传图片成功', res)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 图片上传延迟效果
    slowLoad () {
      setTimeout(() => {
        this.dialogVisible = false
        this.loadImage()
        this.imageUrl = ''
      }, 1000)
    },
    imgAddress (image) {
      console.log('发表文章页面点击', image)
      this.curImgUrl = image.url
    },
    imgConfirm () {
      // 1.确认tab标签是选中了素材库还是上传素材 2.确认图片是否被选中
      if (this.activeName === 'images') {
        console.log(1)
        if (this.curImgUrl) {
          this.coverImageUrl = this.curImgUrl
          this.$message.success('素材库中的图片已选中')
        } else {
          this.$message.error('请先选中一张图片')
        }
      } else {
        if (this.activeName === 'uploads') {
          if (this.imageUrl) {
            this.coverImageUrl = this.imageUrl
          } else {
            this.$message.error('请先上传一张图片')
          }
        }
      }
      this.dialogVisible = false
      this.$emit('input', this.coverImageUrl)
    }
  },
  created () {
    this.loadImage()
  }
}
</script>

<style lang="less" scoped>
.img-btn {
  margin-left: 80px;
  margin-bottom: 20px;
  cursor: pointer;
  width: 150px;
  height: 150px;
  border: 1px dashed #ddd;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
}
  .img_item {
    cursor: pointer;
    position: relative;
    box-sizing: border-box;
  }
  .option {
    position: absolute;
    left: 5px;
    width:180px;
    bottom: 5px;
    height: 30px;
    line-height: 30px;
    background: rgba(0, 0, 0, 0.3);
    text-align: center;
    color: #fff;
    span {
      margin: 0 30px;
      cursor: pointer;
    }
  }
  .red {
    color: red
  }
  .avatar-uploader {
    text-align: center;
  }
  .avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .selected::after{
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.3) url(../assets/selected.png) no-repeat center / 50px 50px;
}
</style>
